<!-- 左侧边栏组件 -->
<template>
  <aside class="sidebar" :class="{ collapsed }">
    <!-- 折叠按钮 - 顶部 -->
    <div class="sidebar-header">
      <el-button 
        circle 
        size="small" 
        @click="$emit('toggle')" 
        :icon="collapsed ? ArrowRight : ArrowLeft"
        class="collapse-btn"
        type="primary"
        plain
      />
    </div>

    <div class="sidebar-content">
      <!-- Element Plus 菜单 -->
      <el-menu
        :default-active="activeMenu"
        :collapse="collapsed"
        :collapse-transition="false"
        background-color="#f8f9fa"
        text-color="#606266"
        active-text-color="#409eff"
        @select="handleMenuSelect"
        class="sidebar-menu"
      >
        <!-- 首页 -->
        <el-menu-item index="home" @click="$router.push('/')">
          <el-icon><House /></el-icon>
          <template #title>首页</template>
        </el-menu-item>

        <!-- 我的知识库 -->
        <el-sub-menu index="my-knowledge">
          <template #title>
            <span style="display: flex; align-items: center; width: 100%;">
              <el-icon><Folder /></el-icon>
              <span style="flex:1;">我的知识库</span>
              <!-- <el-tooltip content="新增知识库" placement="top">
                <el-button
                  size="small"
                  class="add-btn"
                  @click.stop="addKnowledge()"
                  style="width: 28px; min-width: 28px; padding: 0;"
                >+</el-button>
              </el-tooltip> -->
            </span>
          </template>
          
          <!-- 只展示相关部分 -->
          <el-sub-menu 
            v-for="knowledge in myKnowledgeList" 
            :key="knowledge.id"
            :index="`knowledge-${knowledge.id}`"
          >
            <template #title>
              <el-icon><FolderOpened /></el-icon>
              <span
                @click.stop="selectKnowledge(knowledge.id)"
                :class="{ 'selected-knowledge': selectedKnowledgeId === knowledge.id }"
                style="flex:1;cursor:pointer;"
              >{{ knowledge.name }}</span>
              <template v-if="selectedKnowledgeId === knowledge.id">
                <el-tooltip content="新增文档" placement="top">
                  <el-button
                    size="small"
                    class="add-btn"
                    @click.stop="addDocument(knowledge.id)"
                    style="width: 28px; min-width: 28px; padding: 0;"
                  >+</el-button>
                </el-tooltip>
              </template>
            </template>
            
            <!-- 文档列表 -->
            <el-menu-item 
              v-for="doc in knowledge.docs" 
              :key="doc.id"
              :index="`doc-${doc.id}`"
              @click="handleDocClick(knowledge.id, doc.id)"
            >
              <el-icon><Document /></el-icon>
              <template #title>
                <div class="doc-item">
                  <span class="doc-name">{{ doc.name }}</span>
                  <el-dropdown
                      trigger="click"
                      @visible-change="setCurrentDoc(doc)"
                      @click.stop
                  >
                    <el-icon class="more-btn"><MoreFilled /></el-icon>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="handleRenameDoc(doc)">
                          <el-icon><Edit /></el-icon> 重命名
                        </el-dropdown-item>
                        <el-dropdown-item
                            @click="showDeleteConfirm(doc)"
                            class="danger-item"
                        >
                          <el-icon><Delete /></el-icon> 删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-menu-item>
          </el-sub-menu>
          </el-sub-menu>

        <!-- 我共享的文档 -->
        <el-sub-menu index="shared-docs">
          <template #title>
            <el-icon><Share /></el-icon>
            <span>与我共享文档</span>
          </template>
          
          <el-menu-item 
            v-for="doc in sharedDocuments" 
            :key="doc.id"
            :index="`shared-${doc.id}`"
            @click="$router.push(`/shared/${doc.id}`)"
          >
            <el-icon><Document /></el-icon>
            <template #title>{{ doc.name }}</template>
          </el-menu-item>
        </el-sub-menu>

        <!-- AI知识库问答 -->
        <el-menu-item index="ai-chat" @click="$router.push('/ai-chat')">
          <el-icon><el-icon><svg viewBox="0 0 24 24" width="1em" height="1em"><circle cx="12" cy="12" r="10" fill="#409eff"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">AI</text></svg></el-icon></el-icon>
          <template #title>知识库问答</template>
        </el-menu-item>
      </el-menu>
    </div>

    <el-dialog
      v-model="addDocDialogVisible"
      title="新增文档"
      width="400px"
      @close="resetAddDocForm"
    >
      <el-form :model="addDocForm" label-width="80px">
        <el-form-item label="文档名称" required>
          <el-input
            v-model="addDocForm.name"
            placeholder="请输入文档名称"
            :maxlength="50"
            show-word-limit
          />
          <!-- <span style="color: red; margin-left: 4px;">*</span> -->
        </el-form-item>
<!--        <el-form-item label="描述">-->
<!--          <el-input-->
<!--            v-model="addDocForm.description"-->
<!--            placeholder="请输入文档描述"-->
<!--            :maxlength="100"-->
<!--            show-word-limit-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="封面颜色">-->
<!--          <el-input-->
<!--            v-model="addDocForm.color"-->
<!--            placeholder="如 #87c3f9"-->
<!--            :maxlength="20"-->
<!--          />-->
<!--        </el-form-item>-->
        <!-- <el-form-item label="内容"> -->
          <!-- <el-input
            v-model="addDocForm.content"
            type="textarea"
            placeholder="请输入文档内容"
            :rows="3"
          /> -->
        <!-- </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="addDocDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddDocConfirm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="400px"
    >
      <p>确定要删除文档 "{{ docToDelete?.name }}" 吗？此操作不可恢复。</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button
            type="danger"
            @click="confirmDeleteDoc"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>

    <!-- 重命名对话框 -->
    <el-dialog
        v-model="renameDialogVisible"
        title="重命名文档"
        width="400px"
    >
      <el-form :model="renameForm">
        <el-form-item label="新名称">
          <el-input
              v-model="renameForm.name"
              placeholder="请输入新文档名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmRenameDoc"
            :disabled="!renameForm.name.trim()"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </aside>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive} from 'vue'
import { useRoute } from 'vue-router'
import { 
  ElMenu, 
  ElMenuItem, 
  ElSubMenu, 
  ElIcon, 
  ElButton,
  ElTooltip, 
  ElMessageBox, 
  ElMessage 
} from 'element-plus'
import { 
  House, 
  Folder, 
  FolderOpened, 
  Document, 
  Share,
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue'
import { useKnowledgeStore } from '@/stores/knowledge'
import { storeToRefs } from 'pinia'
import { ref } from 'vue'
import {createDocument, deleteDocument, updateDocumentName} from "@/api/document.ts";
import {getUserId} from "@/utils/auth.ts";
import { MoreFilled, Edit, Delete } from '@element-plus/icons-vue'
import router from "@/router";
import type {GetSharedDocumentResponse} from "@/types";
import {useDocumentStore} from "@/stores/document.ts";

// 当前操作的文档
const currentDoc = ref<{id: string, name: string} | null>(null)

// 删除确认对话框
const deleteDialogVisible = ref(false)
const docToDelete = ref<{id: string, name: string} | null>(null)

// 重命名对话框
const renameDialogVisible = ref(false)
const renameForm = reactive({
  id: '',
  name: ''
})

// 设置当前文档（用于操作）
const setCurrentDoc = (doc: {id: string, name: string}) => {
  currentDoc.value = doc
}

// 文档点击处理（避免与下拉菜单冲突）
const handleDocClick = (knowledgeId: string, docId: string, event: Event) => {
  // const isMenuClick = (event.target as HTMLElement).closest('.more-btn')
  // if (!isMenuClick) {
  //   router.push(`/knowledge/${knowledgeId}/${docId}`)
    
  // }
  router.push(`/knowledge/${knowledgeId}/${docId}`)
}

// 显示删除确认
const showDeleteConfirm = (doc: {id: string, name: string}) => {
  docToDelete.value = doc
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDeleteDoc = async () => {
  if (!docToDelete.value) return

  try {
    await deleteDocument(docToDelete.value.id)
    ElMessage.success('删除成功')
    // 刷新文档列表
    const knowledgeStore = useKnowledgeStore()
    await knowledgeStore.fetchKnowledgeList()
  } catch (error) {
    ElMessage.error('删除失败')
  } finally {
    deleteDialogVisible.value = false
  }
}

// 重命名文档
const handleRenameDoc = (doc: {id: string, name: string}) => {

  renameForm.id = doc.id
  renameForm.name = doc.name
  renameDialogVisible.value = true
  console.log(renameForm.id)
}

// 确认重命名
const confirmRenameDoc = async () => {
  try {
    console.log(renameForm.id)
    console.log(renameForm.name)
    await updateDocumentName(renameForm.id, renameForm.name)
    ElMessage.success('重命名成功')
    // 刷新文档列表
    const knowledgeStore = useKnowledgeStore()
    await knowledgeStore.fetchKnowledgeList()
  } catch (error) {
    ElMessage.error('重命名失败')
  } finally {
    renameDialogVisible.value = false
  }
}

interface Props {
  collapsed: boolean
}

defineProps<Props>()
defineEmits<{
  toggle: []
}>()

const route = useRoute()
const knowledgeStore = useKnowledgeStore()

const { knowledgeList: myKnowledgeList } = storeToRefs(knowledgeStore)

const activeMenu = computed(() => {
  const path = route.path
  if (path === '/') return 'home'
  if (path.startsWith('/editor/')) {
    const docId = route.params.documentId as string
    return `doc-${docId}`
  }
  return 'home'
})

// const sharedDocuments = ref([
//   { id: 'shared1', name: '项目需求文档' },
//   { id: 'shared2', name: '技术方案设计' },
//   { id: 'shared3', name: '用户手册' },
//   { id: 'shared4', name: '会议纪要' }
// ])

const documentStore = useDocumentStore();
const sharedDocuments = ref<Array<GetSharedDocumentResponse>>([])
const loadData = async () => {
  try {
    const docs = await documentStore.fetchSharedDocuments(getUserId())
    sharedDocuments.value = docs.map((doc) => ({
      id: doc.id,
      name: doc.name,
      documentId: doc.documentId,
      permissionType: doc.permissionType,
    }))
    console.log(sharedDocuments.value)
  } catch (error) {
    ElMessage.error('获取共享文档失败')
    console.log(error)
  }
}

const handleMenuSelect = (_key: string, _keyPath: string[]) => {
  // console.log('菜单选择:', key, keyPath)
}

onMounted(() => {
  if (myKnowledgeList.value.length === 0) {
    // console.log('侧边栏发现Store为空,正在获取知识库列表...')
    knowledgeStore.fetchKnowledgeList()
  } else {
    // console.log('侧边栏发现Store已有数据,直接使用')
  }
  loadData()
})

// 新增知识库
function addKnowledge() {
  ElMessageBox.prompt('请输入新知识库名称', '新增知识库', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '名称不能为空'
  }).then(({ value }) => {
    const newId = 'k' + Date.now()
    const newKnowledge = {
      id: newId,
      name: value,
      documents: []
    }
    myKnowledgeList.value.push(newKnowledge)
    // 预留后端接口
    // await api.createKnowledge({ name: value })
    ElMessage.success('新增知识库成功')
  }).catch(() => {})
}

// 新增文档弹窗相关
const addDocDialogVisible = ref(false)
const addDocForm = ref({
  name: '',
  content: ''
})
let addDocKnowledgeId: string | null = null

function addDocument(knowledgeId: string) {
  addDocKnowledgeId = knowledgeId
  addDocDialogVisible.value = true
}

function resetAddDocForm() {
  addDocForm.value = {
    name: '',
    content: ''
  }
  addDocKnowledgeId = null
}

async function handleAddDocConfirm() {
  if (!addDocForm.value.name.trim()) {
    ElMessage.error('文档名称为必填项')
    return
  }
  const knowledgeId = addDocKnowledgeId
  if (!knowledgeId) {
    ElMessage.error('未选中知识库')
    return
  }
  // 预留后端接口
  try {
    const res = await createDocument({
      name: addDocForm.value.name,
      knowledgeBaseId: knowledgeId,
      content: addDocForm.value.content || '',
      creatorId: getUserId()?.toString() || ''
    });

    const newDocId = res.id
    // 本地添加
    const knowledge = myKnowledgeList.value.find(k => k.id === knowledgeId)
    if (knowledge) {
      if (!Array.isArray(knowledge.docs)) {
        knowledge.docs = []
      }
      knowledge.docs.push({
        id: newDocId,
        name: addDocForm.value.name,
        content: addDocForm.value.content || ''
      })
      ElMessage.success('新增文档成功')
    }
  } catch (error) {
    ElMessage.error(error)
    console.log(error)
  }
  addDocDialogVisible.value = false
  resetAddDocForm()
}
const selectedKnowledgeId = ref<string | null>(null)
function selectKnowledge(id: string) {
  selectedKnowledgeId.value = id
}
</script>

<style scoped lang="scss">
.sidebar {
  width: 100%;
  flex-shrink: 0;
  height: 100%;
  background: #f8f9fa;
  border-right: 1px solid #ebeef5;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
  position: relative;

  &.collapsed {
    width: 64px;
  }
}

.sidebar-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  
  .collapsed & {
    justify-content: center;
    padding: 12px 8px;
  }
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.sidebar-menu {
  border: none;
  height: 100%;
  
  // 自定义菜单样式
  :deep(.el-menu-item) {
    height: 48px;
    line-height: 48px;
    
    &.is-active {
      background-color: #e8f4ff;
      border-right: 3px solid #409eff;
    }
  }
  
  :deep(.el-sub-menu) {
    .el-sub-menu__title {
      height: 48px;
      line-height: 48px;
    }
  }
  
  // 折叠状态下的样式
  &.el-menu--collapse {
    :deep(.el-sub-menu__title) {
      padding: 0 20px;
    }
    
    :deep(.el-menu-item) {
      padding: 0 20px;
    }
  }
}

.collapse-btn {
  transition: all 0.3s ease;
  
  &:hover {
    transform: scale(1.1);
  }
}

// 自定义滚动条
.sidebar-content::-webkit-scrollbar {
  width: 4px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 2px;
}

.sidebar-content::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}

// 调整Element Plus图标样式
:deep(.el-icon) {
  margin-right: 8px;
}

.add-btn {
  margin-left: 2px;
  vertical-align: middle;
  padding: 0 2px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.selected-knowledge {
  font-weight: bold;
  color: #409eff;
}

.doc-item {
  display: flex;
  align-items: center;
  width: 100%;

  .doc-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .more-btn {
    margin-left: 8px;
    color: #999;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;

    &:hover {
      background: #f0f0f0;
      color: #666;
    }
  }
}

.danger-item {
  color: #f56c6c;

  &:hover {
    color: #f56c6c !important;
  }
}

@media (max-width: 768px) {
  .sidebar {
    transform: translateX(-100%);
    
    &:not(.collapsed) {
      transform: translateX(0);
    }
  }
}
</style>